/*package pt.utl.ist.project_ccu;
import java.util.Map;
import java.util.TreeMap;

import pt.utl.ist.project_ccu.android_libs.Album;
import pt.utl.ist.project_ccu.android_libs.Photo;
import pt.utl.ist.project_ccu.android_libs.SavedData;
import pt.utl.ist.project_ccu.android_libs.Tag;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
 
public class PhoPhotoViewer extends Activity {
    /** Called when the activity is first created. 
	
	private Map<Integer,Integer> _photosID = new TreeMap<Integer,Integer>();
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SavedData.getInstance().updateActivity(this);
        String albumName = getIntent().getStringExtra("Album Name");
        Album album = SavedData.getInstance().getAlbumByName(albumName);
        album.updatePhotos(SavedData.getInstance().getAllPhotos());
        
        int i = 0;
        for (Photo p : album.getPhotos()) {
        	_photosID.put(i, p.getId());
        	++i;
        }
        setContentView(R.layout.grid_layout);
        final GridView gridView = (GridView) findViewById(R.id.grid_view);
        gridView.setAdapter(new ImageAdapter(this));
        setContentView(gridView);
        gridView.setAdapter(new ImageAdapter(this));
 
        gridView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            	showImage(_photosID.get(position),position);
            }
        });
    }
 
    private void showImage(long id, int pos){
    	
        Intent pictureViewer = new Intent(getApplicationContext(), PictureViewer.class);
        pictureViewer.putExtra("pictureId",id );
        pictureViewer.putExtra("picturePosition", pos);

        startActivityForResult(pictureViewer,0);

   }
 
	public class ImageAdapter extends BaseAdapter {
	    int mGalleryItemBackground;
	    private Context mContext;
	 
	    public ImageAdapter(Context c) {
	        mContext = c;
	        TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
	        mGalleryItemBackground = a.getResourceId(
	                R.styleable.HelloGallery_android_galleryItemBackground, 0);
	        a.recycle();
	    }
	 
	    public int getCount() {
	        return _photosID.size();
	    }
	 
	    public Object getItem(int position) {
	        return position;
	    }
	 
	    public long getItemId(int position) {
	        return position;
	    }
	 
	    public View getView(int position, View convertView, ViewGroup parent) {
	        ImageView imageView = new ImageView(mContext);
	        imageView.setImageResource(_photosID.get(position));
	        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
	        imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
	        return imageView;
	    }

 
	}
}*/

package pt.utl.ist.project_ccu;
import java.util.ArrayList;
import java.util.HashMap;

import pt.utl.ist.project_ccu.android_libs.Photo;
import pt.utl.ist.project_ccu.android_libs.SavedData;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewManager;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class PhoPhotoViewer extends Activity {

	//Array que associa o valor de cada checkbox
	//Cada foto tem uma checkbox

	ArrayList<Photo> _photos;
	HashMap<String,Button> buttons;
	Button selectBtn;
	AlertDialog _alertDialog;
	Activity thisActivity;
	GridView gridView;

	//Fotos a serem apresentadas na galeria
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		_photos = (ArrayList<Photo>) getIntent().getSerializableExtra("photos");
		thisActivity = this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.grid_layout_normal);
		gridView = (GridView) findViewById(R.id.grid_view);
		Display display = this.getWindowManager().getDefaultDisplay();
		int _screenWidth,_screenHeight;
		_screenWidth = display.getWidth();
		_screenHeight = display.getHeight();
		gridView.setAdapter(new ImageAdapter(this,_screenHeight));
		int nr_of_images_width = _screenWidth/3;
		gridView.setColumnWidth(nr_of_images_width);

	}
	
	private TextView createDialogTitle() {
		TextView title = new TextView(this);
		// You Can Customise your Title here 
		title.setText("Photo Options");
		title.setBackgroundColor(Color.DKGRAY);
		title.setPadding(10, 10, 10, 10);
		title.setGravity(Gravity.CENTER);
		title.setTextColor(Color.WHITE);
		title.setTextSize(20);
		return title;
	}
	
	private void showDialog(Context context, final int photoPos) {
        if( _alertDialog != null && _alertDialog.isShowing() ) return;
        TextView title = createDialogTitle();
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCustomTitle(title);
        builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int arg1) {
        		Photo photo = _photos.get(photoPos);
        		_photos.remove(photo);
        		SavedData.getInstance().removePhoto(photo);
        		gridView.invalidateViews();
        	}});
        builder.setNeutralButton("Rename", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int arg1) {
        		popWindow(photoPos);
        		dialog.dismiss();
        	}});

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int arg1) {
        		dialog.dismiss();
        	}});
        builder.setCancelable(true);
        _alertDialog = builder.create();
        try {
        	_alertDialog.show();
        }
        catch(Exception e) {}
	}
	

	public void  popWindow(final int photoPos) {

		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(thisActivity);
		View promptsView = li.inflate(R.layout.rename_prompt, null);

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				thisActivity);

		// set prompts.xml to alertdialog builder
		alertDialogBuilder.setView(promptsView);

		EditText userInput = (EditText) promptsView
				.findViewById(R.id.editTextDialogUserInput);
		
		final String photoName = userInput.getText().toString();

		// set dialog message
		alertDialogBuilder
		.setCancelable(false)
		.setPositiveButton("OK",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				Photo photo = _photos.get(photoPos);
				photo.setName(photoName);
				dialog.dismiss();
			}
		})
		.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				dialog.cancel();
			}
		});
		AlertDialog alertDialog = alertDialogBuilder.create();
		try {
			alertDialog.show();
		}
		catch(Exception e) {}
	}

	public class ImageAdapter extends BaseAdapter {
		int mGalleryItemBackground;
		private Context mContext;
		private LayoutInflater mInflater;
		private int _screenHeight;



		public ImageAdapter(Context c, int screenHeight) {
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mContext = c;
			_screenHeight = screenHeight;
		}

		public int getCount() {
			return _photos.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if(convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.galleryitem_normal, null);
				holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
				convertView.setTag(holder);		
			}
			else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			holder.imageview.setId(position);



			holder.imageview.setImageBitmap(
					decodeSampledBitmapFromResource(getResources(), _photos.get(position).getId(), 500, 500));

			holder.imageview.setLayoutParams(new RelativeLayout.LayoutParams(500, (int) (_screenHeight*0.21)));
			holder.imageview.setScaleType(ImageView.ScaleType.FIT_XY);
			holder.id = position;
			
			final int pos = position;
			
			holder.imageview.setOnClickListener(new OnClickListener() {

				public void onClick(View arg0) {
					showImage(_photos.get(pos));
				}

			});
			
			holder.imageview.setOnLongClickListener(new OnLongClickListener() {

				public boolean onLongClick(View arg0) {
					
					showDialog(thisActivity, pos);
					return true;
				}

			});

			return convertView;
		}
		
	    private void showImage(Photo photo){
	    	
	        Intent pictureViewer = new Intent(getApplicationContext(), PictureViewer.class);
	        pictureViewer.putExtra("photo",photo );
	        startActivityForResult(pictureViewer,0);

	   }

		public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
			int width = bm.getWidth();
			int height = bm.getHeight();
			float scaleWidth = ((float) newWidth) / width;
			float scaleHeight = ((float) newHeight) / height;
			// CREATE A MATRIX FOR THE MANIPULATION
			Matrix matrix = new Matrix();
			// RESIZE THE BIT MAP
			matrix.postScale(scaleWidth, scaleHeight);

			// "RECREATE" THE NEW BITMAP
			Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
			return resizedBitmap;
		}

		public int getScale(int originalWidth,int originalHeight,
				final int requiredWidth,final int requiredHeight)
		{
			//a scale of 1 means the original dimensions 
			//of the image are maintained
			int scale=1;

			//calculate scale only if the height or width of 
			//the image exceeds the required value.
			if((originalWidth>requiredWidth) || (originalHeight>requiredHeight)) 
			{
				//calculate scale with respect to
				//the smaller dimension
				if(originalWidth<originalHeight)
					scale=Math.round((float)originalWidth/requiredWidth);
				else
					scale=Math.round((float)originalHeight/requiredHeight);

			}

			return scale;
		}

		public int calculateInSampleSize(
				BitmapFactory.Options options, int reqWidth, int reqHeight) {
			// Raw height and width of image
			final int height = options.outHeight;
			final int width = options.outWidth;
			int inSampleSize = 1;

			if (height > reqHeight || width > reqWidth) {
				if (width > height) {
					inSampleSize = Math.round((float)height / (float)reqHeight);
				} else {
					inSampleSize = Math.round((float)width / (float)reqWidth);
				}
			}
			return inSampleSize;
		}
		
		public Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
				int reqWidth, int reqHeight) {

			// First decode with inJustDecodeBounds=true to check dimensions
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeResource(res, resId, options);

			// Calculate inSampleSize
			options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

			// Decode bitmap with inSampleSize set
			options.inJustDecodeBounds = false;
			return BitmapFactory.decodeResource(res, resId, options);
		}
	}

	class ViewHolder {
		ImageView imageview;
		int id;
	}
}
